package com.example.canteen.dao.impl;

import com.example.canteen.dao.StudentDao;
import com.example.canteen.domain.Student;
import com.example.canteen.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public Student findById(int id) {
        Student student = null;
        String sql = "SELECT id,PASSWORD,NAME,sex,statement FROM student WHERE id=?";
        try {
            student =template.queryForObject(sql,new BeanPropertyRowMapper<Student>(Student.class),id);
        }catch (Exception e){

        }
        return student;
    }

    @Override
    public List<Student> findAll() {
        String sql = "SELECT id,PASSWORD,NAME,sex,statement FROM student";
        return template.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
    }

    @Override
    public int delete(int id) {
        String sql = "DELETE FROM student WHERE id=?";
        return template.update(sql,id);
    }

    @Override
    public void save(Student student) {
        String sql = "insert into student(id,password,name,sex,statement) value(?,?,?,?,?)";
        template.update(sql,student.getId(),
                student.getPassword(),
                student.getName(),
                student.getSex(),
                student.getStatement());
    }

    @Override
    public int update(Student student) {
        String sql = "UPDATE student SET PASSWORD=?,NAME=?,sex=?,statement=? WHERE id=?";
        return template.update(sql, student.getPassword(),
                student.getName(),
                student.getSex(),
                student.getStatement(),
                student.getId());
    }

    @Override
    public Student findByUsernameAndPassword(int id, String password) {
        Student student = null;
        String sql = "SELECT id,PASSWORD,NAME,sex,statement FROM student WHERE id=? and password=?";
        student =template.queryForObject(sql,new BeanPropertyRowMapper<Student>(Student.class),id,password);
        return student;

    }
}
